package com.mini.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * sentinel限流配置:
 * 导入的 com.alibaba.cloud.sentinel.gateway模块的SentinelSCGAutoConfiguration
 * 会自动配置 SentinelGatewayBlockExceptionHandler和SentinelGatewayFilter，
 * 如果自己注入SentinelGatewayFilter会报错 bean has already been defined bug，所以直接使用依赖内的bean
 *
 * @author Zhou Feng
 */
@Configuration
public class SentinelGatewayConfig {

    @PostConstruct
    public void doInit(){
        initBlockHandlers();
        //initGatewayRules();
        //initCustomizedApis();
    }

    /**
     * 自定义限流异常回调
     */
    public void initBlockHandlers(){
        BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
            Map<String, Object> map = new HashMap<>(3);
            map.put("code",-1);
            map.put("msg","当前请求过多！");
            map.put("success", false);
            map.put("route", serverWebExchange.getRequest().getURI().getPath());
            return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(map));
        };
        //注册被限流的回调
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    /**
     * 设置限流规则，对路由或者API分组限流
     */
    private void initGatewayRules(){
        HashSet<GatewayFlowRule> rules = new HashSet<>();
        rules.add(
                new GatewayFlowRule("ReactiveCompositeDiscoveryClient_mini-admin")
                .setCount(1)
                .setIntervalSec(1)
        );
        GatewayRuleManager.loadRules(rules);
    }

    /**
     * 自定义API分组
     */
    private void initCustomizedApis() {
        Set<ApiDefinition> definitions = new HashSet<>();
        ApiDefinition api1 = new ApiDefinition("mini-admin")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/mini-admin/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        ApiDefinition api2 = new ApiDefinition("mini-auth")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/mini-auth/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        definitions.add(api1);
        definitions.add(api2);
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }
}
